<?php
namespace app\common\model;
use app\common\exception\BaseException;
use think\Request;
use think\Cache;
use think\Db;

/**
 * 微信小程序模型
 */
class Wxapp extends BaseModel
{
    protected $name = 'wxapp';
	
	/**
     * 账号来源
     */
    public function getSourceAttr($value)
    {
        $status = [10 => '自助注册', 20 => '平台注册'];
        return ['text' => $status[$value], 'value' => $value];
    }
	
	/**
     * 是否授权
     */
    public function getIsEmpowerAttr($value)
    {
        $status = ['未授权','已授权'];
        return ['text' => $status[$value], 'value' => $value];
    }
	
	/**
     * 自定义底部授权信息
     */
    public function getIsCopyrightAttr($value)
    {
        $status = ['关闭','开启'];
        return ['text' => $status[$value], 'value' => $value];
    }
	
	/**
     * 小程序类型
     */
    public function getAppTypeAttr($value)
    {
		$app_type = WebEdition::getAppType($value);
        return ['text' => $app_type['name'], 'value' => $app_type['app_type']];
    }
	
	/**
     * 小程序类型
     */
    public function getShopModeAttr($value)
    {
		$status = [10 => '单门店', 20 => '多门店'];
        return ['text' => $status[$value], 'value' => $value];
    }
	
	/**
     * 设置小程序模板信息
     */
    public function getTemplateAttr($value)
    {
		if($value==0){
			return ['template_id' => $value];
		}
		return Template::detail($value);
         
    }
	
	/**
     * 到期时间
     */
    public function getExpireTimeAttr($value)
    {
		$day = round(($value - time()) / 86400);
        return ['text' => date("Y-m-d", $value), 'value' => $value, 'day' => $day];
    }
	
	/**
     * 获取列表 
     */
    public function getList($store_user_id=0)
    {
		// 筛选条件
        $filter = [];
        $store_user_id > 0 && $filter['store_user_id'] = $store_user_id;
        // 执行查询
        $list = $this->useGlobalScope(false)
            ->where($filter)
            ->order('wxapp_id','desc')
            ->paginate(15, false, [
                'query' => Request::instance()->request()
            ]);
        return $list;
    }
	
    /**
     * 获取小程序信息
     */
    public static function detail()
    {
        return self::get([]);
    }
	
	/**
     * 获取小程序信息 - 回调接口
     */
    public static function getWxapp($where)
    {
        return self::useGlobalScope(false)->where($where)->find();
    }

    /**
     * 从缓存中获取小程序信息
     */
    public static function getWxappCache($wxapp_id = null)
    {
        if (is_null($wxapp_id)) {
            $self = new static();
            $wxapp_id = $self::$wxapp_id;
        }
        if (!$data = Cache::get('wxapp_' . $wxapp_id)) {
            $data = self::get($wxapp_id);
            if (empty($data)) throw new BaseException(['msg' => '未找到当前小程序信息']);
            Cache::set('wxapp_' . $wxapp_id, $data);
        }
        return $data;
    }

    /**
     * 创建小程序
     */
    public function add($data)
    {
		if(!isMobile($data['phone'])){
			$this->error = '手机号码错误';
            return false;	
		}
		$edition = WebEdition::detail($data['web_edition_id']);//获取版本详情
		$store = StoreUser::detail($data['store_user_id']);//获取商户详情
		$pay = 0;//支付费用
		if($data['year']>0){
			//计算费用
			if($data['shop_mode']==10){
				//单商户
				if($store['wallet'] < $edition['buy_single'][$data['year']]){
					$this->error = '账户余额不足，请充值';
					return false;
				}
				$pay = $edition['buy_single'][$data['year']];
			}
			if($data['shop_mode']==20){
				//多商户
				if($store['wallet'] < $edition['buy_many'][$data['year']]){
					$this->error = '账户余额不足，请充值';
					return false;
				}
				$pay = $edition['buy_many'][$data['year']];
			}
			$data['expire_time'] = strtotime('+'.$data['year'].'year');//计算到期时间
		}else{
			$data['expire_time'] = time()+$edition['trial_day']*3600*24;//计算到期时间
		}
		$data['app_type'] = $edition['app_type'];
		// 开启事务
        Db::startTrans();
        try {
			//扣费
			$store->wallet = ['dec',$pay];
			$store->save();
			// 添加小程序记录
			$this->allowField(true)->save($data);
			// 新增小程序diy配置
			$Page = new WxappPage;
			$Page->insertDefault($this->wxapp_id,$data);
			// 新增默认门店
			$Shop = new Shop;
			$Shop->insertDefault($this->wxapp_id,$data);
			// 新增用户等级
			$UserGrade = new UserGrade;
			$UserGrade->insertDefault($this->wxapp_id);
			// 新增小程序帮助
			$WxappHelp = new WxappHelp;
			$WxappHelp->insertDefault($this->wxapp_id);
			Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }

}
